package dgut.haitaobao.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dgut.haitaobao.vo.param.ShoppingCartParamsVO;
import dgut.haitaobao.service.ShoppingCartService;
import dgut.haitaobao.util.response.HttpResponse;
import dgut.haitaobao.vo.param.ShoppingCartUpdateCartNumParamVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
@CrossOrigin
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;


    //获得购物车列表信息
    @PostMapping("/getShoppingCarts")
    public HttpResponse getShoppingCarts(@RequestBody String userId,@RequestHeader("token")String token) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(userId);
        String userIdStr = jsonNode.get("userId").asText();
        return shoppingCartService.getShoppingCarts(userIdStr);
    }

    //添加购物车信息
    @PostMapping("/addShoppingCart")
    public HttpResponse addShoppingCart(@RequestBody ShoppingCartParamsVO shoppingCartParamsVO, @RequestHeader("token")String token){
        shoppingCartParamsVO.setCartTime(new Date());
        return shoppingCartService.addShoppingCar(shoppingCartParamsVO);

    }
    
    //修改购物车商品数量
    @PostMapping("/updateCartNum")
    public HttpResponse updateCartNum(@RequestBody ShoppingCartUpdateCartNumParamVO paramVO,@RequestHeader("token")String token){
        return shoppingCartService.updateCartNumByCartId(paramVO);
    }

    //查询购物车列表信息根据购物车id
    @PostMapping("/getShoppingCartListByCartIds")
    public HttpResponse getShoppingCartListByCartIds(@RequestBody String cartIds,@RequestHeader("token")String token) throws JsonProcessingException {
        //System.out.println(cartIds);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(cartIds);
        String cartIdsText = jsonNode.get("cartIds").asText();
        String[] cartIdsSplit = cartIdsText.split(",");
        List<Integer> cartIdsInt=new ArrayList<>();
        for (int i = 0; i < cartIdsSplit.length; i++) {
            cartIdsInt.add(Integer.parseInt(cartIdsSplit[i]));
        }
        return shoppingCartService.getShoppingCartsByCartIds(cartIdsInt);
    }


    @RequestMapping("/deleteShoppingCart")
    public HttpResponse deleteShoppingCart(@RequestBody String cartId) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(cartId);
        String cartIdStr = jsonNode.get("cartId").asText();
        return shoppingCartService.deleteShoppingCart(Integer.parseInt(cartIdStr));
    }
}
